package com.health.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.healthcommon.pojo.Permission;
import com.healthcommon.pojo.Role;
import com.healthcommon.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Set;

@Component
public class MySecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findUserByUsername(username);
        if(user == null){
            return null;
        }
        ArrayList<GrantedAuthority> list = new ArrayList();
        Set<Role> roles = user.getRoles();
        for (Role r:roles
             ) {
//            授权角色
            list.add(new SimpleGrantedAuthority(r.getKeyword()));
            Set<Permission> permissions = r.getPermissions();
            for (Permission p:permissions
                 ) {
//                授权权限
                list.add(new SimpleGrantedAuthority(p.getKeyword()));
            }
        }
        org.springframework.security.core.userdetails.User userDetails =
                new org.springframework.security.core.userdetails.User(username, user.getPassword(), list);
        return userDetails;
    }

}
